<template>
	<view class="body">
		<view style="height: 20rpx;"></view>
		<Calendar ref="calendarRef" :eventList="recorderList" @dateChange='dateChange'>
			<WeekList ref="weekListRef" :currentDate="searchDate" @change="onWeekChange" />
		</Calendar>
		<scroll-view scroll-y class="list-scroll" @scrolltolower="loadData()">
			<view class="list">
				<view class="list-item" v-for="(item, index) in recorderList" :key="index">
					<view class="item-top">
						<view class="title" :class="{'title-disable': item.disable}">{{ item.title }}</view>
						<!-- <image v-if="!item.disable" class="edit" src="@/img/yangcan/ic_edit.png"
							@click="toReservationInfo"></image> -->
					</view>
					<view class="item-content">
						<view class="info">
							<view class="label">
								<image v-if="!item.disable" class="icon" src="@/img/yangcan/ic_timer.png"></image>
								<image v-else class="icon" src="@/img/yangcan/ic_timer_disable.png"></image>
								<text class="text">预约时间</text>
							</view>
							<view class="value">{{ item.timeRange }}</view>
						</view>
						<view class="info">
							<view class="label">
								<image v-if="!item.disable" class="icon" style="margin-right: 12rpx;"
									src="@/img/yangcan/ic_address.png" mode="heightFix"></image>
								<image v-else class="icon" style="margin-right: 12rpx;"
									src="@/img/yangcan/ic_address_disable.png" mode="heightFix"></image>
								<text class="text">预约地址</text>
							</view>
							<view class="value">{{ item.address }}</view>
						</view>
						<view class="info">
							<view class="label">
								<image v-if="!item.disable" class="icon" src="@/img/yangcan/ic_phone.png"></image>
								<image v-else class="icon" src="@/img/yangcan/ic_phone_disable.png"></image>
								<text class="text">预约电话</text>
							</view>
							<view class="value">{{ item.phone }}</view>
						</view>
					</view>
					<view class="item-bottom">
						<view v-if="item.reserveState == 2 || item.reserveState == 4" class="btn">已取消</view>
						<view v-else-if="item.isExpire" class="btn">已过期</view>
						<view v-else-if="item.reserveState == 1" class="btn" @click="onCancelReservation(item)">取消
						</view>
						<view v-else-if="item.reserveState == 3" class="btn">审核中</view>
						<view v-else-if="item.reserveState == 5" class="btn">已核销</view>
					</view>
				</view>
				<view class="footer-tip" v-if="!loading && recorderList.length == 0">暂无数据~</view>
				<view class="footer-tip" v-if="loading">正在加载...</view>
				<view class="footer-tip" v-if="noMoreData && recorderList.length != 0">没有更多数据了</view>
			</view>
		</scroll-view>
		<view class="add-wrapper" @click="toReservationInfo">
			<image src="@/img/yangcan/ic_add_reservation.png"></image>
		</view>

		<ReservationPopup type="dialog" title="提示" :content="dialogContent" :cancelText="cancelText"
			:confirmText="confirmText" :show="isShow" @updateShow="e => isShow = e" @cancel="onCancel"
			@confirm="onConfirm" />
	</view>
</template>

<script>
	import Calendar from '@/components/calendar/index.vue';
	import WeekList from '@/components/calendar/week-list.vue';
	import ReservationPopup from '@/components/reservation-popup/index.vue';
	import * as ReservationApi from '@/api/reservation/index.js';
	import StorageUtils from '@/utils/StorageUtils';
	import CacheConfig from '@/config/CacheConfig';
	import {
		showInfo
	} from '@/utils/ToastUtils';

	export default {
		data() {
			return {
				recorderList: [],
				selectedRecord: null,
				isShow: false,
				page: 1,
				pageSize: 10,
				searchDate: new Date(),
				loading: false,
				noMoreData: false,
			}
		},
		components: {
			ReservationPopup,
			Calendar,
			WeekList
		},
		onShow() {
			this.page = 1;
			this.pageSize = 10;
			this.loading = false;
			this.noMoreData = false;
			this.recorderList = [];
			this.loadData();
			this.$refs.calendarRef.initData();
			setTimeout(() => {
				this.$refs.weekListRef.initData();
			}, 500)
		},
		computed: {
			dialogContent() {
				if (!!this.selectedRecord && this.selectedRecord.isTimeOut) {
					return '您好！由于您预定体验的时间不足6小时， 无法自动取消，需与相关门店协商决定， 感谢您的理解！';
				} else {
					return '是否取消该预约!';
				}
			},
			cancelText() {
				if (!!this.selectedRecord && this.selectedRecord.isTimeOut) {
					return '返回'
				} else {
					return '取消';
				}
			},
			confirmText() {
				if (!!this.selectedRecord && this.selectedRecord.isTimeOut) {
					return '发送申请'
				} else {
					return '确定';
				}
			}
		},
		methods: {
			loadData() {
				if (this.loading || this.noMoreData) return;
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				const {
					start,
					end
				} = this.getDayTimeRange(this.searchDate);
				console.log(start, end);
				const param = {
					userId: userInfo.id,
					current: this.page,
					size: this.pageSize,
					searchStart: start,
					searchEnd: end,
				};
				this.loading = true;
				ReservationApi.getReservationPage(param).then(res => {
					console.log("res", res.obj);
					if (!!res.obj) {
						const currentDate = new Date();
						const list = res.obj.records.map(v => {
							const startDate = new Date(v.startTime);
							let disable = false;
							let isTimeOut = this.isSixHoursApart(currentDate, startDate);
							console.log("isTimeOut", isTimeOut);
							let isExpire = false;
							if (currentDate.getTime() > startDate.getTime()) {
								disable = true;
								isExpire = true;
							}
							if (v.reserveState == 5 || v.reserveState == 2 || v.reserveState == 4) {
								disable = true;
							}
							const name = v.reserveItemVo?.itemName || "未知";
							return {
								...v,
								title: `${name}体验预约`,
								time: `${v.startTime}`,
								timeRange: `${v.startTime}-${this.$u.timeFormat(v.endTime, 'hh:MM:ss')}`,
								name: name,
								address: v.reserveItemVo?.center?.name || '未知',
								disable,
								isExpire,
								isTimeOut,
							}
						});
						console.log("list", list);
						if (list.length == 0) {
							this.noMoreData = true;
						} else {
							this.recorderList = [...this.recorderList, ...list];
							this.page++;
						}
					}
				}).finally(() => {
					this.loading = false;
				})
			},
			isSixHoursApart(time1, time2) {
				// 将时间字符串转换为Date对象
				const startDate = new Date(time1);
				const endDate = new Date(time2);
				// 计算时间差（毫秒）
				const timeDiff = endDate - startDate;
				// 将时间差转换为小时
				const hoursDiff = timeDiff / (1000 * 60 * 60);
				// 判断是否超过6小时
				return hoursDiff < 6;
			},
			getDayTimeRange(date = new Date()) {
				// 确保 date 参数是一个 Date 对象
				const targetDate = typeof date === 'string' || typeof date === 'number' ? new Date(date) : date;
				console.log("targetDate", targetDate);
				// 获取日期部分（年、月、日）
				const year = targetDate.getFullYear();
				const month = String(targetDate.getMonth() + 1).padStart(2, '0');
				const day = String(targetDate.getDate()).padStart(2, '0');
				// 构建开始时间（00:00:00）
				const start = `${year}-${month}-${day} 00:00:00`;
				// 构建结束时间（23:59:59）
				const end = `${year}-${month}-${day} 23:59:59`;
				return {
					start,
					end
				};
			},
			onWeekChange(e) {
				console.log("onWeekChange", e);
				this.page = 1;
				this.pageSize = 10;
				this.loading = false;
				this.noMoreData = false;
				this.recorderList = [];
				const date = `${e.year}-${e.month}-${e.day}`;
				this.searchDate = new Date(date);
				this.loadData();
			},
			dateChange(e) {
				console.log("dateChange", e);
				this.searchDate = new Date(e);
				this.page = 1;
				this.pageSize = 10;
				this.loading = false;
				this.noMoreData = false;
				this.recorderList = [];
				this.loadData();
				this.$refs.weekListRef.initData();
				this.$refs.calendarRef.initData();
			},
			onCancelReservation(item) {
				this.isShow = true;
				this.selectedRecord = item;
			},
			onCancel() {
				this.isShow = false;
				setTimeout(() => {
					this.selectedRecord = null;
				}, 200)
			},
			onConfirm() {
				const cancelTime = this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss');
				const param = {
					id: this.selectedRecord.id,
					reserveState: 2,
					cancelTime,
				};
				ReservationApi.setResrvationState(param).then(res => {
					this.isShow = false;
					const index = this.recorderList.findIndex(v => v.id == this.selectedRecord.id);
					if (this.selectedRecord.isTimeOut) {
						this.recorderList[index].reserveState = 3;
					} else {
						this.recorderList[index].reserveState = 2;
						this.recorderList[index].disable = true;
					}
					showInfo("提交成功！");
				})
			},
			toReservationInfo() {
				// 获取当前日期和搜索日期
				const today = new Date();
				const searchDate = this.searchDate;
				const maxDate = new Date();
				maxDate.setMonth(maxDate.getMonth() + 3);
				console.log("maxDate", maxDate);
				console.log("searchDate", searchDate);
				let dateText = '';
				if (searchDate <= today) {
				  console.log('搜索日期小于等于今天');
				  dateText = this.formatDate(today);
				} else if (searchDate > maxDate) {
				  console.log('搜索日期超过最大允许日期');
				  dateText = this.formatDate(today);
				} else {
				  console.log('搜索日期在有效范围内');
				  dateText = this.formatDate(searchDate);
				}
				console.log('最终日期:', dateText);
				uni.navigateTo({
					url: '/pages/oxygen/reservation-info?date=' + dateText
				})
			},
			formatDate(date) {
			  if (!(date instanceof Date) || isNaN(date.getTime())) {
			    return '';
			  }
			  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			}

		}
	}
</script>

<style lang="scss">
	.body {
		height: 100vh;
		background-color: #f2f2f2;
	}

	.list-scroll {
		height: calc(100% - 315rpx);
		margin-top: calc(315rpx - 226rpx);
	}

	.list {
		height: auto;
		padding: 38rpx 30rpx;

		.list-item {
			width: 100%;
			height: 380rpx;
			border-radius: 20rpx;
			background-color: #fff;
			padding: 0 25rpx;
			box-sizing: border-box;
			margin-bottom: 30rpx;

			.item-top {
				display: flex;
				align-items: center;
				padding: 25rpx 0;
				border-bottom: 1rpx solid #e5e5e5;

				.title {
					flex: 1;
					font-family: PingFang;
					font-weight: bold;
					font-size: 33rpx;
					color: #f98816;
				}

				.title-disable {
					color: #a9a9a9 !important;
				}

				.edit {
					width: 33rpx;
					height: 33rpx;
				}
			}



			.item-content {
				padding: 14rpx 12rpx;
				background-color: #f9fbfc;
				border-radius: 10rpx;
				margin-top: 8rpx;

				.info {
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;

					.label {
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						background-color: #f2f2f2;
						width: 146rpx;
						height: 47rpx;

						.icon {
							width: 25rpx;
							height: 25rpx;
							margin: 0 8rpx;
						}

						.text {
							font-family: PingFang;
							font-weight: bold;
							font-size: 21rpx;
							color: #000000;
							margin-right: 20rpx;
						}
					}
				}

				.info:last-child {
					margin-bottom: 0;
				}

				.value {
					margin-left: 30rpx;
					font-family: PingFang;
					font-weight: 400;
					font-size: 24rpx;
					color: #888888;
				}
			}

			.item-bottom {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				margin-top: 17rpx;

				.btn {
					width: 164rpx;
					height: 63rpx;
					background-color: #f2f2f2;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-family: PingFang;
					font-weight: bold;
					font-size: 33rpx;
					color: #717171;
					margin-left: 15rpx;
				}

				.primary {
					color: #f08800;
				}
			}
		}

		.list-item:last-child {
			margin-bottom: 0;
		}

		.footer-tip {
			font-size: 30rpx;
			font-weight: 400;
			text-align: center;
			padding-top: 5rpx;
		}
	}

	.add-wrapper {
		width: 120rpx;
		height: 120rpx;
		position: fixed;
		right: 40rpx;
		bottom: 50rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>
